package kpi.java_training.testing.user;

import kpi.java_training.testing.db.FileLoader;
import kpi.java_training.testing.db.FileSaver;
import kpi.java_training.testing.db.QuestionLoader;
import kpi.java_training.testing.db.QuestionSaver;
import kpi.java_training.testing.questions.QuestionList;

import java.io.File;

/**
 * Class which gets user name at the start of the program
 */
public class UserData {
    private final String DEFAULT_QUESTIONS_FILE = "questions";
    private final String USER_FILE_EXTENSION = ".usr";
    private String userName;
    private QuestionLoader loader;

    public UserData(String userName) {
        this.userName = userName;
        loader = null;
    }

    public String getUserName() {
        return userName;
    }

    public QuestionList getNewQuestions() {
        QuestionList questions = getQuestions(DEFAULT_QUESTIONS_FILE,"noType");
        questions.shuffle();
        return questions;
    }
    public QuestionList getNewQuestions(String type) {
        QuestionList questions = getQuestions(DEFAULT_QUESTIONS_FILE+type+".txt",type);
        questions.shuffle();
        return questions;
    }

    public QuestionList getSavedQuestions(String type) {
        return getQuestions(getInputFileName(),type);
    }

    public int getSavedAnswers(QuestionList questions) {
        return loader.loadAnswers(questions);
    }

    private QuestionList getQuestions(String fileName,String type) {
        loader = new FileLoader(fileName);

        return loader.getQuestions(type);
    }

    public void saveSession(String session) {
        QuestionSaver saver = new FileSaver(getUserFileName());
        saver.saveSession(session);
    }

    private String getUserFileName() {
        return userName + USER_FILE_EXTENSION;
    }

    public boolean userDataExists() {
        File f = new File(getUserFileName());
        return f.exists();
    }

    private String getInputFileName() {
        if (userDataExists()) {
            return getUserFileName();
        } else {
            return DEFAULT_QUESTIONS_FILE;
        }
    }

}
